from app.common.auth import get_token_user
from app.common.errors import ApiError
from starlette.middleware.base import BaseHTTPMiddleware


class AuthCheckMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        from app.models.user import User as UserModel

        try:
            token_user = get_token_user(request, parse_token=True)
            user_obj = UserModel.create_without_data(auto_id=token_user.id)
            await user_obj.refresh_from_db()
        except ApiError:
            user_obj = None
        request.state.user = user_obj
        request.state.authenticated = True if user_obj else False
        response = await call_next(request)
        return response
